/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package open.kiwipeach.autoconfigure.swagger;

import cn.kiwipeach.blog.enums.ValueEnum;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.WebMvcRequestHandler;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class BlogSwaggerConfiguration {


    @Value("${runtimeMode}")
    private String runtimeMode;

    private Predicate<RequestHandler> customPredicate = new Predicate<RequestHandler>() {
        @Override
        public boolean apply(RequestHandler input) {
            // 规则一：添加注解 @ApiOperation
            if (!input.isAnnotatedWith(ApiOperation.class)) return false;
            // 规则二：报名不在demo下
            if (input instanceof WebMvcRequestHandler) {
                WebMvcRequestHandler handler = (WebMvcRequestHandler) input;
                HandlerMethod handlerMethod = handler.getHandlerMethod();
                if (handlerMethod.getBeanType().getName().contains(".demo.")) return false;
            }
            return true;
        }
    };


    @Bean
    public Docket docket() {
        List<ResponseMessage> responseMessages = new ArrayList<ResponseMessage>();
        responseMessages.add(new ResponseMessageBuilder().code(HttpServletResponse.SC_OK).message("操作成功").build());
        responseMessages.add(new ResponseMessageBuilder().code(HttpServletResponse.SC_NOT_FOUND).message("资源不存在").build());
        responseMessages.add(new ResponseMessageBuilder().code(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).message("服务器异常").build());
        Predicate<RequestHandler> selector = ValueEnum.DEV.getCode().equals(runtimeMode) ? RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class) : customPredicate;
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET, responseMessages)
                .globalResponseMessage(RequestMethod.POST, responseMessages)
                .globalResponseMessage(RequestMethod.DELETE, responseMessages)
                .select()
                // 扫描含有ApiOperation.class注解的控制器
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .apis(selector)
                .paths(PathSelectors.any())
                .build();
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return new Function<Class<?>, Boolean>() {
            @Override
            public Boolean apply(Class<?> input) {
                return ClassUtils.getPackageName(input).startsWith(basePackage);
            }
        };
    }

    private ApiInfo apiInfo() {
        String envInfo = ValueEnum.DEV.getCode().equals(runtimeMode) ? "开发环境" : "生产环境";
        return new ApiInfoBuilder().title("nice-blog-sys 接口服务列表(" + envInfo + ")").version("2020-SPRING").description("Nice Blog System 是一个基于Java开发，“便捷轻巧、高性能、外形Nice”的博客系统").build();
    }
}
